﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate UInt32 DllRegUnRegAPI();

        [DllImport("Kernel32.dll", CallingConvention = CallingConvention.StdCall)]
        static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string strLibraryName);

        [DllImport("Kernel32.dll", CallingConvention = CallingConvention.StdCall)]
        static extern Int32 FreeLibrary(IntPtr hModule);

        [DllImport("Kernel32.dll", CallingConvention = CallingConvention.StdCall)]
        static extern IntPtr GetProcAddress(
            IntPtr hModule,
            [MarshalAs(UnmanagedType.LPStr)] string lpProcName
        );

        public MainWindow()
        {
            InitializeComponent();
        }

        string ocxPath = @"E:\LenovoSoftstore\Install\CADkantu_jisuban_\cad.ocx";

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Hello World!");
            Register(ocxPath);
        }

        //public static bool Register(string filePath)
        //{
        //    IntPtr hModule = LoadLibrary(filePath);
        //    if (hModule == IntPtr.Zero)
        //        return false;

        //    IntPtr proc = GetProcAddress(hModule, "DllRegisterServer");
        //    if (proc == IntPtr.Zero)
        //    {
        //        FreeLibrary(hModule);
        //        return false;
        //    }

        //    var func = (DllRegUnRegAPI)
        //        Marshal.GetDelegateForFunctionPointer(proc, typeof(DllRegUnRegAPI));
        //    UInt32 hr = func();
        //    FreeLibrary(hModule);
        //    return hr == 0; // S_OK typically equals 0
        //}
        public static bool Register(string filePath)
        {
            try
            {
                ProcessStartInfo psi = new ProcessStartInfo();
                psi.FileName = "regsvr32.exe";
                psi.Arguments = $" \"{filePath}\""; // /s 表示静默模式
                psi.UseShellExecute = true;
                psi.Verb = "runas"; // 请求管理员权限

                Process process = Process.Start(psi);
                process.WaitForExit();

                return process.ExitCode == 0;
            }
            catch
            {
                return false;
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e) { }
    }
}
